package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.Column;
import com.ruoyi.system.mapper.ColumnMapper;
import com.ruoyi.system.service.ColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ColumnServiceImpl implements ColumnService {
    @Autowired
    private ColumnMapper columnMapper;
    @Override
    public List<Column> selectColumnList(Column column) {
        return columnMapper.selectColumnList(column);
    }
    /**
     * 查询栏目树结构信息*/
    @Override
    public List<TreeSelect> selectColumnTreeList(Column column)
    {
        List<Column> columns = SpringUtils.getAopProxy(this).selectColumnList(column);
        return buildColumnTreeSelect(columns);
    }
    //构建前端所需要树结构
    @Override
    public List<Column> buildColumnTree(List<Column> columns) {
        List<Column> returnList = new ArrayList<>();
        List<Long> tempList = columns.stream().map(Column::getColumnId).collect(Collectors.toList());
        for (Column column:columns)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(column.getParentId()))
            {
                recursionFn(columns, column);
                returnList.add(column);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = columns;
        }
        return returnList;
    }

  //  构建前端所需要下拉树结构
    @Override
    public List<TreeSelect>  buildColumnTreeSelect(List<Column> columns) {
//        List<Column> columnTress = buildColumnTree(columns);
//       return columnTress.stream().map(TreeSelect::new).collect(Collectors.toList());
        return null;

    }
    //递归列表
    private void recursionFn(List<Column> columns, Column column) {
        List<Column> childList = getChildList(columns, column);
        column.setChildren(childList);
        for (Column tChild : childList)
        {
            if (hasChild(columns, tChild))
            {
                recursionFn(columns, tChild);
            }
        }
    }
//判断是否有子节点
    private boolean hasChild(List<Column> columns, Column tChild) {
        return getChildList(columns,tChild).size()>0;
    }
//得到子节点
    private List<Column> getChildList(List<Column> columns, Column column) {
          List<Column> tlist = new ArrayList<Column>();
          Iterator<Column> it = columns.iterator();
          while (it.hasNext())
          {
            Column n = (Column) it.next();
              if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == column.getColumnId().longValue())
              {
                  tlist.add(n);
              }
          }
          return tlist;
    }

    @Override
    public boolean checkColumnNameUnique(Column column) {
        if (column == null || StringUtils.isBlank(column.getColumnName())) {
            return UserConstants.NOT_UNIQUE;
        }
        Long currentId = column.getColumnId();
        Column existing = columnMapper.checkColumnNameUnique(column.getColumnName());

        if (existing != null) {
            if (currentId == null || !existing.getColumnId().equals(currentId)) {
                return UserConstants.NOT_UNIQUE;
            }
        }
        return UserConstants.UNIQUE;
    }
    @Override
    public int insertColumn(Column column) {
        column.setCreateBy(SecurityUtils.getUsername());
        return columnMapper.insertColumn(column);
    }
    @Override
    public int updateColumn(Column column) {
        column.setUpdateBy(SecurityUtils.getUsername());
        return columnMapper.updateColumn(column);
    }
    @Override
    @Transactional
    public int deleteColumnById(Long columnId) {
        // 先删除子栏目
        List<Long> childIds = columnMapper.selectChildColumnIdsByParentId(columnId);
        for (Long childId : childIds) {
            columnMapper.deleteColumnById(childId);
        }
        // 再删除当前栏目
        return columnMapper.deleteColumnById(columnId);
    }
    @Override
    public Column selectColumnById(Long columnId) {

        return columnMapper.selectColumnById(columnId);
    }
    @Override
    @Transactional
    public void hideChildColumns(Long parentId) {
        updateChildVisible(parentId, "1");  // 1-隐藏
    }

    @Override
    @Transactional
    public void showChildColumns(Long parentId) {
        updateChildVisible(parentId, "0");  // 0-显示
    }

    // 批量更新子栏目可见性
    private void updateChildVisible(Long parentId, String visible) {
        List<Long> childIds = columnMapper.selectChildColumnIdsByParentId(parentId);
        String updateBy = SecurityUtils.getUsername();
        for (Long childId : childIds) {
            columnMapper.updateColumnVisibleColumnId(childId, visible, updateBy);
        }
    }
    @Override
    public List<Column> selectChildColumnsByParentId(Long parentId) {
        return columnMapper.selectChildColumnsByParentId(parentId);
    }
    //验证栏目下是否有文章
 public boolean hasArticleUnderColumn(Long columnId){
        Integer count = columnMapper.hasArticleUnderColumn(columnId);
        return count !=null && count>0;
 }
    // 先删子栏目，再删自身；或直接删关联数据
    @Override
    public int deleteColumnCascade(Long columnId) {
        //  校验：如果有文章，不允许删除
        if (hasArticleUnderColumn(columnId)) {
          throw new Error("该栏目或子栏目下存在文章，无法删除");
        }
        // 校验：若为一级栏目，检查是否存在子栏目
        Column column = selectColumnById(columnId);
        if (column != null && (column.getParentId() == null || column.getParentId() == 0)) {
            boolean hasChildren = hasAnyChildColumns(columnId);
            if (hasChildren) {
                throw new RuntimeException("一级栏目存在子栏目，无法删除，请先删除所有子栏目");
            }
        }
        // 递归删除子栏目（针对非一级栏目的子栏目）
        List<Long> childColumnIds = columnMapper.selectChildColumnIds(columnId);
        for (Long childId : childColumnIds) {
            deleteColumnCascade(childId);
        }
        // 删除当前栏目
        return columnMapper.deleteById(columnId);
    }


    //隐藏接口时进行验证
    @Override
    public boolean hasUnHiddenChildren(Long columnId) {
     List<Long> allChildIds = columnMapper.selectAllChildColumnIds(columnId);
     if(allChildIds.isEmpty()){
         return false;
     }
     for(Long childId:allChildIds){
         Column child = columnMapper.selectColumnById(childId);
         if (child != null && "0".equals(child.getVisible())) {
             return true; // 存在未隐藏的子栏目
         }
     }
        return false;
    }
    private boolean hasAnyChildColumns(Long columnId) {
        List<Long> allChildIds = columnMapper.selectAllChildColumnIds(columnId);
        return !allChildIds.isEmpty();
    }
}



